package com.farm.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.farm.aop.Operation;
import com.farm.aop.Type;
import com.farm.aop.aopUpdate;
import com.farm.common.BaseContext;
import com.farm.common.States;
import com.farm.mapper.LoveMapper;
import com.farm.mapper.VideoMapper;
import com.farm.pojo.*;
import com.farm.pojo.DTO.VideoDto;
import com.farm.service.LogsService;
import com.farm.service.UserService;
import com.farm.service.VideoService;
import com.farm.common.AppHttpCodeEnum;
import com.farm.common.ResponseResult;
import com.sun.org.apache.xerces.internal.dom.PSVIDocumentImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author farm
 * @since 2023-10-30
 */
@Slf4j
@RestController
@RequestMapping("/video")
public class VideoController {
    @Autowired
    private VideoService videoService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private RedisTemplate<Object,Object> template;

    @Autowired
    private UserService userService;

    @Autowired
    private LogsService logsService;
    @Autowired
    private LoveMapper loveMapper;
    @Autowired
    private VideoMapper videoMapper;

    @Value("${video.basePath}")
    private String uploadPath;

    @Value("${video.linkPath}")
    private String uploadLink;

    public void logsKeep(){
        Logs logs = new Logs();
        logs.setOperate("对视频进行操作");
        logsService.save(logs);
    }

    @GetMapping("/admin/getListWhatYouWant")
    public ResponseResult getListWhatYouWant(){

        return ResponseResult.okResult(videoService.list());
    }

    @GetMapping("/admin/getlist")
    public ResponseResult adminGetList(){
        return ResponseResult.okResult(videoService.list());
    }
    @GetMapping("/user/getWant")
    public ResponseResult getWant(){
        LambdaQueryWrapper<Video> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Video::getState, States.ENABLE).orderByDesc(Video::getLiking);
        List<Video> videoList = videoMapper.selectList(lqw).subList(0, 6);
        return ResponseResult.okResult(videoList);
    }


//    @aopUpdate(TypeValue = Type.VIDEO, OperationValue = Operation.UPDATE)
    @PostMapping("/admin/update")
    public ResponseResult update(@RequestBody Video video){
        videoService.updateById(video);
        logsKeep();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @PostMapping("/getmylist")
    public ResponseResult getMyList(@RequestBody User user){
        return ResponseResult.okResult(videoService.list(Wrappers.<Video>lambdaQuery().eq(Video::getUserId,user.getUserId())));
    }

    /**
     * 用户获取所有视频列表（已经审核）
     * @return
     */
    @GetMapping("/user/getlist")
    public ResponseResult getList(){
        return ResponseResult.okResult(videoService.getUserList());
    }




    /**
     * 显示查询数据
     * @param videoList
     * @return
     */
    private List<VideoDto> Inquiry(List<Video> videoList){
        // 查询当前用户点赞内容
        Long CurrentUserId = BaseContext.getCurrentId();
        QueryWrapper<love> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("video_id as videoId, liking");
        queryWrapper.lambda().eq(love::getUserId, CurrentUserId).isNotNull(love::getVideoId).orderByAsc(love::getVideoId);
        List<Map<String, Object>> mapList = loveMapper.selectMaps(queryWrapper);
        // 定义mapList下标
        int indexList = 0;
        boolean flag = true;
        if(mapList.size() == 0){
            flag = false;
        }

        List<VideoDto> videoDtoList = new ArrayList<>();
        for (Video video : videoList){
            // 封装返回值InquiryDto
            VideoDto videoDto = new VideoDto();
            BeanUtils.copyProperties(video, videoDto);
            videoDto.setLikeState(States.DISABLE);
            // 保持查询结果的健壮性
            if (flag){
                while(true){
                    if(video.getVideoId().compareTo((Long)mapList.get(indexList).get("videoId")) < 0){
                        break;
                    }else if(video.getVideoId().equals(mapList.get(indexList).get("videoId"))){
                        // 点赞结果判断
                        if(mapList.get(indexList).get("liking") == States.ENABLE)
                        {
                            videoDto.setLikeState(States.ENABLE);
                        }
                        indexList++;
                        if(mapList.size() <= indexList ){
                            indexList = 0;
                            flag = false;
                        }
                        break;
                    }else {
                        indexList++;
                        if(mapList.size() <= indexList ){
                            indexList = 0;
                            flag = false;
                            break;
                        }
                    }

                }

            }
            videoDtoList.add(videoDto);
        }
        return videoDtoList;
    }


    /**
     * 显示分区视频数据
     * @param id
     * @return
     */
    @GetMapping("/user/getListByPartitions/{id}")
    public ResponseResult getListByPartitions(@PathVariable String id){
        System.out.println(id);
        LambdaQueryWrapper<Video> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Video::getState, States.ENABLE).orderByAsc(Video::getVideoId);
        if (id != null && !id.equals("")){
            lqw.eq(Video::getPartitions, Long.valueOf(id));
        }
        List<Video> videoList = videoMapper.selectList(lqw);
        if (videoList == null || videoList.size() == 0){
            return null;
        }
        List<VideoDto> videoDtoList = Inquiry(videoList);
        return ResponseResult.okResult(videoDtoList);
    }

//    @GetMapping("/user/getListByPartitions/{id}")
//    public ResponseResult getListByPartitions(@PathVariable String id){
//        System.out.println(id);
//        return ResponseResult.okResult(videoService.list(
//                Wrappers.<Video>lambdaQuery()
//                        .eq(Video::getPartitions,Long.valueOf(id))
//                        .eq(Video::getState,1)
//        ));
//    }

    /**
     * 视频点赞功能的实现
     * @param videoId
     * @param liking
     */
    @GetMapping("/addLove")
    @Transactional
    public void addLove(@RequestParam Long videoId, @RequestParam Integer liking, @RequestParam Long userId) {
        // 查询视频表更新视频数据
        Video video = videoMapper.selectById(videoId);
        // 如果是0则是取消点赞
        if (liking.equals(States.DISABLE)) {
            video.setLiking(video.getLiking() - 1);
        } else if (liking.equals(States.ENABLE)) {
            // 如果是1则是点赞
            video.setLiking(video.getLiking() + 1);
        }
//        System.out.println("这里是点赞：" + BaseContext.getCurrentId());
        // 插入数据
        videoMapper.updateById(video);

        LambdaQueryWrapper<love> lqw = new LambdaQueryWrapper<>();
        lqw.eq(love::getVideoId, videoId).eq(love::getUserId, userId);
        List<love> loves = loveMapper.selectList(lqw);

        if (loves.size() == 0) {
            // 如果不存在则直接构造插入
            love loveNew = love.builder()
                    .userId(userId)
                    .videoId(videoId)
                    .liking(liking)
                    .build();
            loveMapper.insert(loveNew);
        } else {
            love loveOne = loves.get(0);
            loveOne.setLiking(liking);
            loveMapper.updateById(loveOne);
        }
    }


    @PostMapping("/push")
    public ResponseResult upload(@RequestBody Video video){
        Long userId = video.getUserId();
        User user = userService.getById(userId);
        video.setUserName(user.getUsername());
        video.setPath(uploadLink + "/" + video.getPath() );
        videoService.save(video);
        logsKeep();

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

//    @aopUpdate(TypeValue = Type.VIDEO, OperationValue = Operation.UPDATE)
    @PostMapping("/admin/changeState")
    public ResponseResult changeState(@RequestBody Video video){
//        template.opsForValue().set(video.getVideoId() + "", JSON.toJSONString(video));
//        kafkaTemplate.send("farm.video",video.getVideoId().toString());
        videoService.updateById(video);
        logsKeep();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @PostMapping("/delete")
//    @aopUpdate(TypeValue = Type.VIDEO, OperationValue = Operation.DELETE)
    public ResponseResult delete(@RequestBody Video video){
        boolean b = videoService.removeById(video.getVideoId());
        logsKeep();
        return b?ResponseResult.okResult(AppHttpCodeEnum.SUCCESS):ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @PostMapping("/uploadVideo")
    public ResponseResult handleVideoUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"上传的视频文件为空");
        }

        // 检查文件类型
        if (!file.getContentType().startsWith("video")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"请上传有效的视频文件");
        }

        // 检查文件大小
        if (file.getSize() > 50 * 1024 * 1024) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"视频文件大小不能超过50MB");
        }

        try {
            // 将视频文件保存到服务器
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + suffix;
            File dir = new File(uploadPath);
            if (!dir.exists()){
                // 文件不存在开始创建
                dir.mkdir();
            }
            log.info("上传成功");
            // 在这里，你可以进一步处理保存成功后的逻辑，比如将文件路径保存到数据库
            file.transferTo(new File(uploadPath + filename));
            return ResponseResult.okResult(filename);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"视频文件上传失败");
        }
    }
}

